package model

import (
	"database/sql"
	"context"
	"log"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-redis/redis/v8"
	"github.com/go-ini/ini"
)

var (
	db *sql.DB
	rdb *redis.Client
	err error
	ctx = context.Background()
)

func init() {
	cfg, err := ini.Load("config/conf.ini")
	if err != nil {
		log.Println(err)
	}

	mysqlServer := cfg.Section("mysql").Key("Server").String()
	mysqlPassword := cfg.Section("mysql").Key("Password").String()
	mysqlPort := cfg.Section("mysql").Key("Port").String()

	OpenDb(mysqlServer, mysqlPassword, mysqlPort)

	redisAddr := cfg.Section("redis").Key("Addr").String()
	redisPassword := cfg.Section("redis").Key("Password").String()
	redisDB, _ := cfg.Section("redis").Key("DB").Int()

	NewRedisClient(redisAddr, redisPassword, redisDB)
}

func OpenDb(mysqlServer string, mysqlPassword string, mysqlPort string) error {
	sqlUrl := "root:" + mysqlPassword + "@tcp(" + mysqlServer + ":" + mysqlPort + ")/thick_snow?charset=utf8"

	db, err = sql.Open("mysql", sqlUrl)
	if err != nil {
		panic(err.Error())
	}

	return nil
}

func NewRedisClient(redisAddr string, redisPassword string, redisDB int) error {
	rdb = redis.NewClient(&redis.Options{
		Addr: redisAddr,
		Password: redisPassword,
		DB: redisDB, 
	})

	pong, err := rdb.Ping(ctx).Result()

	if err != nil {
		log.Printf("connect redis failed", err)
		return err
	}

	log.Printf("redis ping result: %s\n", pong)
	return nil
}
